import accounting from 'accounting';
import { connect } from 'dva';
import uuid from 'es6-uuid';
import PropTypes from 'prop-types';
import React from 'react';
import myStyle from '../index.less';
import { TableC, ExportC } from '../../../../comps';

class LimitDetailTableC extends React.PureComponent {
  // props默认值
  // eslint-disable-next-line react/static-property-placement
  static defaultProps = {
    isRed: false, // 是否需要触警行标红
    search: {}, // 查询条件
  };

  constructor(props) {
    super(props);

    this.state = {
      search: {},
      timeStamp: undefined, // 时间戳
      expandedRowKeys: [], // 展开的key
      columns: [],
      dataSource: [],
      columnsChild: [],
      tableLoading: false,
    };
  }

  componentDidMount() {
    this.setState(
      {
        search: this.props.search,
        timeStamp: this.props.timeStamp,
      },
      () => {
        this.getDetails(); // 获取详情数据
      },
    );
  }

  // eslint-disable-next-line react/no-deprecated
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(this.state.timeStamp) != JSON.stringify(nextProps.timeStamp) || JSON.stringify(this.state.search) != JSON.stringify(nextProps.search)) {
      this.setState(
        {
          search: nextProps.search,
          timeStamp: nextProps.timeStamp,
          expandedRowKeys: [], // 展开的key
        },
        () => {
          this.getDetails(); // 获取详情数据
        },
      );
    }
  }

  // 获取详情表格信息 最外层的信息
  getDetails = () => {
    const { dispatch, url } = this.props;
    const { search } = this.state;
    const args = {
      parentId: search.detailId,
    };
    this.setState({
      tableLoading: true,
    });
    dispatch({
      type: url,
      payload: {
        ...args,
      },
      callback: (data) => {
        data?.dataSource?.map((item) => (item.key = uuid(16)));
        this.setState({
          dataSource: data?.dataSource || [],
          columns: data?.columns || [],
        });
        this.setState({
          tableLoading: false,
        });
      },
    });
  };

  // 点击展开二级菜单 进行请求
  onNestedExtend = (expanded, record) => {
    const { dispatch, url } = this.props;
    if (!expanded) return; // 如果关闭即返回
    if (record.child?.columns) return; // 如果有数据就返回
    // 获取穿透信息
    dispatch({
      type: url,
      payload: {
        parentId: record.detailId,
      },
      callback: (resData) => {
        if (resData.dataSource?.length) {
          resData.dataSource.map((item) => {
            item.key = uuid(16);
          });
        }
        const formatData = (dataSource) => {
          for (let index = 0; index < dataSource.length; index++) {
            const item = dataSource[index];
            if (item.key == record.key) {
              // 找到当前行 设置item的子项
              item.child = {
                columns: resData.columns || [],
                dataSource: resData.dataSource || [],
              };
              return item;
            }
            if (item.child && item.child.columns?.length) {
              formatData(item.child.dataSource || []);
            }
          }
        };
        formatData(this.state.dataSource);
        this.setState({
          dataSource: [...this.state.dataSource],
        });
      },
    });
  };

  // 子表渲染的内容
  expandedRowRender = (record) => {
    const { child } = record;
    if (child?.columns) {
      const columns = child?.columns;
      columns.map((item) => {
        if (['detailValue', 'marginValue', 'prohibitValue', 'numerator', 'denominator'].includes(item.key)) {
          // eslint-disable-next-line no-shadow
          item.render = (text, record) => {
            if (record.pecentView === false) {
              return text !== null ? text.toFixed(2) : '--';
            }
            return text !== null ? (['numerator', 'denominator'].includes(item.key) ? text.toFixed(2) : `${accounting.formatNumber(Number(text) * 100, 2)}%`) : '--';
          };
        }
      });
    }
    return (
      <TableC
        columns={child ? child.columns || [] : undefined}
        dataSource={child ? child.dataSource || [] : undefined}
        expandedRowRender={this.expandedRowRender} // 递归调用
        onExpand={(expanded, record) => this.onNestedExtend(expanded, record)}
        rowClassName={(record) => (record.lastLevel ? myStyle.noExpend : '')} // 无子项 设置样式
        hidePage={true}
        rowKey='key'
      />
    );
  };

  render() {
    const { search, scrollHeight } = this.props;
    if (this.state.columns) {
      const { columns } = this.state;
      columns.map((item) => {
        // 数值类型的 要区分展示百分比还是原值
        if (['detailValue', 'marginValue', 'prohibitValue', 'numerator', 'denominator'].includes(item.key)) {
          item.render = (text, record) => {
            if (record.pecentView === false) {
              return text !== null ? text.toFixed(2) : '--';
            }
            return text !== null ? (['numerator', 'denominator'].includes(item.key) ? text.toFixed(2) : `${accounting.formatNumber(Number(text) * 100, 2)}%`) : '--';
          };
        }
      });
    }
    return (
      <div>
        <div style={{ position: 'absolute', top: '130px', right: '36px' }}>
          <ExportC url='gateway/risk-postcheck/risk/result/export' search={{ parentId: search.detailId }} disabled={!(this.state.dataSource && this.state.dataSource?.length)} />
        </div>
        <TableC
          columns={this.state.columns || []}
          dataSource={this.state.dataSource || []}
          hidePage={true}
          scroll={{ y: scrollHeight }}
          loading={this.state.tableLoading}
          rowKey='key'
          expandedRowRender={this.expandedRowRender}
          onExpand={(expanded, record) => this.onNestedExtend(expanded, record)}
          rowClassName={(record) => (record.lastLevel ? myStyle.noExpend : '')} // 无子项 设置样式
        />
      </div>
    );
  }
}

// props类型
LimitDetailTableC.propsTypes = {
  isRed: PropTypes.bool, // 是否需要触警行标红
  scrollHeight: PropTypes.oneOf([PropTypes.string, PropTypes.number]), // 设置表格滚动高度
  search: PropTypes.object, // 当前查询条件
};

export default connect(({ limitDetailTableM, loading }) => ({ limitDetailTableM, loading }))(LimitDetailTableC);
